package com.wondream.springboot.gridfs.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.wondream.springboot.gridfs.domain.ImageResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.whereFilename;

/**
 * @author wondream
 * @version 1.0
 * @create 2022/10/16 3:46 PM
 */
@RestController
public class ImageController {

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private GridFsOperations operations;

    @Autowired
    private GridFSBucket gridFSBucket;

    @PostMapping("file/upload")
    public ImageResponse upload(@RequestParam("file") MultipartFile file) {
        DBObject metaData = new BasicDBObject();
        // 把时间戳作为文件名存入mongodb
        String fileName = String.valueOf(System.currentTimeMillis());
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            gridFsTemplate.store(inputStream, fileName, "image", metaData);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return new ImageResponse(fileName);
    }

    @GetMapping(value = "file/download/${fileName}", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(@PathVariable("fileName") String fileName) throws IOException {
        if (fileName == null) {
            return null;
        }
        // 根据文件名查询(也可以根据md5值等信息查询)
        GridFSFindIterable result = operations.find(query(whereFilename().is(fileName)));
        GridFSFile gridFSFile = result.first();
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsResource，用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        return IOUtils.toByteArray(gridFsResource.getInputStream());
    }
}
